package cn.sinokj.party.chineseFourParty.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.AreaSelectionActivity;
import cn.sinokj.party.chineseFourParty.activity.ArticleListActivity;
import cn.sinokj.party.chineseFourParty.activity.ExamListActivity;
import cn.sinokj.party.chineseFourParty.activity.IndexImageWebActivity;
import cn.sinokj.party.chineseFourParty.activity.LoginInActivity;
import cn.sinokj.party.chineseFourParty.activity.MainActivity;
import cn.sinokj.party.chineseFourParty.activity.OpinionListActivity;
import cn.sinokj.party.chineseFourParty.activity.SearchActivity;
import cn.sinokj.party.chineseFourParty.activity.XListTabActivity;
import cn.sinokj.party.chineseFourParty.adapter.HomeAdapter;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.bean.HomeDataBean;
import cn.sinokj.party.chineseFourParty.fragment.base.BaseFragment;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.Constans;
import cn.sinokj.party.chineseFourParty.view.MyTextSliderView;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by l on 2017/11/12.
 */

public class HomeFragment extends BaseFragment {
    private static final int GET_AD = 1;
    private static final int GET_FLAG = 2;
    private static final int GET_HOME_DATA = 3;
    private static final int GET_PERMISSION = 4;
    //@BindView(R.id.title)
    //public TextView titleText;
    @BindView(R.id.rv_home)
    public RecyclerView rvHome;
    @BindView(R.id.topbar_right_img)
    public ImageButton topbarRightImg;
    Unbinder unbinder;
    @BindView(R.id.status_bar_height)
    View statusBarHeight;
    @BindView(R.id.x_refresh)
    XRefreshView xRefresh;
    private boolean isloadPic;
    private MainActivity activity;
    private SliderLayout sliderLayout;
    private final int title = R.id.title;
    private boolean isFirst = false;
    private HomeAdapter homeAdapter;
    private HomeDataBean homeDataBean;
    private HomeDataBean.ObjectsBean.ModuleListBean clickModule;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.main, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initImmersionBar(statusBarHeight);
        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (MainActivity) getActivity();
        initRefresh();
        //new Thread(new LoadDataThread(GET_HOME_DATA)).start();
    }

    private void initRefresh() {
        xRefresh.setPullLoadEnable(false);
        xRefresh.setSilenceLoadMore(false);
        //设置刷新完成以后，headerview固定的时间
        xRefresh.setPinnedTime(1000);
        xRefresh.setMoveForHorizontal(true);
        xRefresh.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                isFirst = false;
                new Thread(new LoadDataThread(GET_HOME_DATA)).start();
                xRefresh.stopRefresh(true);
            }
        });
    }

    @OnClick({R.id.topbar_right_img, R.id.left_select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.topbar_right_img:
                if (App.loginStatus) {
                    startActivity(new Intent(activity, SearchActivity.class));
                } else {
                    startActivity(new Intent(activity, LoginInActivity.class));
                }
                break;
            case R.id.left_select:
                startActivity(new Intent(activity, AreaSelectionActivity.class));
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg) {
        switch (msg.what) {
            case Constans.HOME_REFRESH:
                isFirst = false;
                new Thread(new LoadDataThread(GET_HOME_DATA)).start();
                break;
        }
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case GET_HOME_DATA:
                return HttpDataService.getHomeData(App.nCommitteeId);
            case GET_PERMISSION:
                return HttpDataService.getVerfityModule(clickModule.nId, App.nCommitteeId);
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        String json = jsonObject.toString();
        switch (msg.what) {
            case GET_HOME_DATA:
                homeDataBean = new Gson().fromJson(json, HomeDataBean.class);
                initView();
                break;
            case GET_PERMISSION:
                int nRes = jsonObject.optInt("nRes");
                if (nRes == 1) {
                    jumpToNext(clickModule.vcModule, clickModule.nTemplate, clickModule.nId, clickModule.vcJumpLink);
                } else {
                    Toast.makeText(activity, "暂无权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void initView() {
        if (sliderLayout == null) {
            sliderLayout = new SliderLayout(activity);
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            int height = wm.getDefaultDisplay().getHeight();
            sliderLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height * 210 / 667));
        }
        sliderLayout.removeAllSliders();
        for (final HomeDataBean.ObjectsBean.ArticleListBean articleListBean : homeDataBean.objects.articleList) {
            MyTextSliderView sliderView = new MyTextSliderView(activity);
            sliderView.image(articleListBean.vcPath);
            sliderView.description(articleListBean.vcTitle);
            sliderLayout.addSlider(sliderView);
            sliderLayout.setDuration(5000);
            //设置指示器的位置
            sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
            sliderView.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                @Override
                public void onSliderClick(BaseSliderView slider) {
                    Intent intent = new Intent(activity, IndexImageWebActivity.class);
                    intent.putExtra("url", articleListBean.url);
                    intent.putExtra("icon", articleListBean.vcPath);
                    //   intent.putExtra("title", articleListBean.vcTitle);
                    intent.putExtra("topTitle", "要闻");
                    intent.putExtra("describe", articleListBean.vcDescribe);
                    startActivity(intent);
                }
            });
        }

        if (isFirst) {
            for (int i = 0; i < homeAdapter.getData().size(); i++) {
                homeAdapter.getData().get(i).unRead = homeDataBean.objects.moduleList.get(i).unRead;
            }
            homeAdapter.notifyDataSetChanged();
        } else {
            isFirst = true;
            //titleText.setVisibility(View.VISIBLE);
            //titleText.setText(homeDataBean.objects.committee.vcPartyAppName);
            topbarRightImg.setVisibility(View.VISIBLE);
            int rvHomeheight = rvHome.getHeight();
            int sliderLayoutHeight = sliderLayout.getLayoutParams().height;
            int rvHomeLeftheight = rvHomeheight - sliderLayoutHeight;
            if (homeAdapter == null) {
                homeAdapter = new HomeAdapter(rvHomeLeftheight, homeDataBean.objects.moduleList, homeDataBean.objects.committee.nModuleType);
                homeAdapter.addHeaderView(sliderLayout);
            } else {
                homeAdapter.removeHeaderView(sliderLayout);
                homeAdapter = new HomeAdapter(rvHomeLeftheight, homeDataBean.objects.moduleList, homeDataBean.objects.committee.nModuleType);
                homeAdapter.addHeaderView(sliderLayout);
            }
            homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    clickModule = homeDataBean.objects.moduleList.get(position);
                    new Thread(new LoadDataThread(GET_PERMISSION, clickModule.nId)).start();

                }
            });

            GridLayoutManager gridLayoutManager = new GridLayoutManager(activity, homeDataBean.objects.committee.nModuleType);
            rvHome.setLayoutManager(gridLayoutManager);
            rvHome.setAdapter(homeAdapter);


        }
    }


    private void jumpToNext(String vcModule, int nTemplate, int nId, String vcJumpLink) {
        Intent intent = new Intent();
        switch (nTemplate) {
            case 1: //1是新闻
                intent.setClass(activity, XListTabActivity.class);
                intent.putExtra("functionType", vcModule);
                intent.putExtra("nId", nId);
                activity.startActivity(intent);
                break;
            case 2:    //2是答题
                intent.setClass(activity, ExamListActivity.class);
                intent.putExtra("functionType", vcModule);
                intent.putExtra("type", 2);
                activity.startActivity(intent);
                break;
            case 3:    //3是网页
                intent.setClass(activity, IndexImageWebActivity.class);
                intent.putExtra("url", vcJumpLink);
                intent.putExtra("icon", "");
                intent.putExtra("newsTitle", "");
                intent.putExtra("topTitle", vcModule);
                intent.putExtra("nShared", 2);
                intent.putExtra("describe", "");
                intent.putExtra("isRush", true);
                /*if (nId == 63) {
                    intent.putExtra("showClose", true);
                }*/
                activity.startActivity(intent);
                break;
            case 4:    //4是意见征集
                if (App.loginStatus) {
                    intent.setClass(activity, OpinionListActivity.class);
                    activity.startActivity(intent);
                } else {
                    Toast.makeText(activity, "请登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case 5:    //5是三会一课
                intent.setClass(activity, ArticleListActivity.class);
                activity.startActivity(intent);
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        new Thread(new LoadDataThread(GET_HOME_DATA)).start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}
